package com.animal.ws;

import com.animal.entity.AnUser;
import com.animal.entity.Message;
import com.animal.utils.MessageUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigretor.class)

//将这个类交给spring去管理
@Component
public class ChatEndpoint {

    //用来存储每一个客户端对象对应的ChatEndpoint对象
    private  static Map<String,Object> onlineUser=new ConcurrentHashMap<>();
    //声明session对象,通过此对象可以发送消息给指定的用户
    private  Session session;
    //声明一个Httpsession对象,里面存储了用户名
    private HttpSession httpSession;
    @OnOpen
    //建立连接时被调用
    public void onOpen(Session session, EndpointConfig config){

        this.session=session;
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        System.out.println( httpSession.getAttribute("user"));
        this.httpSession=httpSession;
        //从httpsession对象中获取用户名
        AnUser user = (AnUser) httpSession.getAttribute("user");
        System.out.println(user.toString());
        String username=user.getUsername();
        System.out.println(user.getUsername());
        //将对象存储到容器中
        onlineUser.put(username,this);
        //将当前在线用户的用户名推送给所有客户端
        String message = MessageUtils.getMessage(true,null,getNames());
        //调用方法进行消息的推送
        broadcastAllUsers(message);

    }
    private void broadcastAllUsers(String message) {

            Set<String> names=onlineUser.keySet();
            for(String name:names){

                ChatEndpoint chatEndpoint= (ChatEndpoint) onlineUser.get(name);
                RemoteEndpoint.Basic basicRemote = chatEndpoint.session.getBasicRemote();
                try {
                    basicRemote.sendText(message);
            }
        catch (Exception e){
            e.printStackTrace();
        }
            }
    }
    //获得所有的在线用户
    private Set<String> getNames(){
        return onlineUser.keySet();
    }
    @OnMessage
    //接收到客户端发送的消息时调用
      public void onMessage(String message,Session session){

        try {
            //        将message转化为message对象
            ObjectMapper mapper=new ObjectMapper();
            Message mess=mapper.readValue(message,Message.class);
            //获取消息的接收者
            String toName=mess.getToName();
            //获取消息数据
            String data=mess.getMessage();
            //获取消息的发送者
            AnUser user = (AnUser) httpSession.getAttribute("user");
            String username= user.getUsername();
            //格式化推送的数据
            String message1 = MessageUtils.getMessage(false, username, data);
            //发送数据
            ChatEndpoint chatEndpoint = (ChatEndpoint) onlineUser.get(toName);
            chatEndpoint.session.getBasicRemote().sendText(message1);

        }catch (Exception e){
            e.printStackTrace();
        }


    }
    @OnClose
    //关闭连接时调用
    public void onClose(Session session){
        AnUser user = (AnUser) httpSession.getAttribute("user");
        String username= user.getUsername();
        //从容器中删除指定的用户
        onlineUser.remove(username);
        //显示在线的人 系统推送
        String message = MessageUtils.getMessage(true, null, getNames());
        broadcastAllUsers(message);

    }

}
